<template>
  <div class="scoring-module">
    <!--
    <div class="header">
      <div class="title">个人飞行赛-选手计分页面</div>
      <img class="ico-logo" src="@/assets/logo-fii.png" />
    </div>
    -->
    <div class="content">
      <div class="flying-race-box">
        <div class="flying-race-logo-wrap">
          <img class="flying-race-logo" src="@/assets/logo-race.png" />
        </div>
        <div class="flying-race-info">
          <div class="flying-race-title">{{ contestInfo.matchName || '' }}</div>
          <div class="flying-race-labels">
            <div class="flying-race-label">科目：{{ contestInfo.matchItemName || '-' }}</div>
          </div>
          <div class="flying-race-tags">
            <!-- <div class="flying-race-tag">{{ contestInfo.matchItemName || '-' }}</div> -->
            <div class="flying-race-tag">{{ queryForm.type === 'group' ? contestInfo.teamName : contestInfo.userName || '-' }}</div>
            <div class="flying-race-tag">{{ queryForm.id || '-' }}</div>
            <div class="flying-race-tag">{{ queryForm.type === 'group'? '' : contestInfo.company || '-' }}</div>
          </div>
        </div>
      </div>

      <div class="form-query-box">
        <div class="form-box">
          <div class="form-item">
            <span class="form-item-label">{{queryForm.type==='group'? '团队' : '学员'}}ID：</span>
            <el-input class="form-item-val" v-model="queryForm.id" placeholder="" @blur="handleQuery" disabled></el-input>
          </div>
          <div class="form-item">
            <span class="form-label">比赛场地：</span>
            <el-input class="form-item-val" v-model="queryForm.site" placeholder="" disabled></el-input>
          </div>
          <!-- <el-button class="btn-query" @click="handleQuery" type="primary">查询</el-button> -->
          <el-button class="btn-reset" @click="handleCancel" type="default">重置</el-button>
        </div>
        <div class="scoring-box">
          <el-button class="btn-scoring" @click="handleScoring" type="primary">计分</el-button>
          <div class="scoring-count">{{ currScore || 0 }}</div>
          <div class="scoring-unit">分</div>
        </div>
      </div>

      <div class="scoring-table-box bee-box">
        <div class="scoring-table-title"></div>
        <div class="scoring-table-wrap">
          <el-table class="scoring-table" :data="beeData" :span-method="spanMethod" :header-cell-style="{ background: '#F5F7FA', color: '#333', }">
            <el-table-column :prop="beeItem.prop" :label="beeItem.label" :align="beeItem.align" :width="beeItem.width" v-for="(beeItem, beeIdx) in beeColumn" :key="beeIdx">
              <template #default="scope">
                <div class="scoring-dimension-box" v-if="beeItem.prop === 'name'">
                  <div class="scoring-dimension-name">
                    <span>{{ scope.row[beeItem.prop] }}</span>
                    <span v-if="!['base', 'time', 'num'].includes(scope.row.key)">：{{ scope.row.score || '' }}<span class="scoring-dimension-tips">（去掉最高、最低分后的平均分）</span></span>
                  </div>
                  <div class="scoring-dimension-label">{{ scope.row.label }}</div>
                </div>
                <div class="scoring-base-info" v-else-if="beeItem.prop === 'teacherScore1' && ['base', 'time', 'num'].includes(scope.row.key)">
                  <el-radio-group v-model="scope.row.score" :disabled="isBaseZero && scope.row.key !== 'base'" class="scoring-radio" @change="onScoreChange(scope.row)">
                    <el-radio :value="config.val" v-for="(config, idx) in scoreConfigMap[scope.row.key]" :key="idx">{{ config.label }}</el-radio>
                  </el-radio-group>
                </div>
                <el-input v-else v-model.number="scope.row[beeItem.prop]" :disabled="isBaseZero" class="scoring-ipt" :class="isGameOver ? 'scoring-ipt-wran' : ''" type="number" :min="0" :max="scoreConfigMap[scope.row.key]" @blur="onScoreBlur(scope.row, beeItem.prop, scoreConfigMap[scope.row.key])" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="scoring-end" v-if="isGameOver">比赛结束</div>
      </div>

      <div class="form-btns-box">
        <el-button class="form-btn btn-cancel" @click="handleCancel" type="default">取消</el-button>
        <el-button class="form-btn btn-submit" @click="handleSubmit" type="primary">提交</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, watch, onMounted, computed, } from "vue";
import {ElMessage} from "element-plus";
import baseService from "@/service/baseService";
import { useRoute } from 'vue-router';

const contestInfo = ref({
  id: '',
  company: '',
  matchItemName: '',
  matchItemTeamId: '',
  matchName: '',
  userId: '',
  userName: '',
  teamName: '',
});
const userInfo = ref({
  name: '',
  code: '',
  school: '',
});

const queryForm = reactive({
  id: '',
  site: '',
  type: '',
});

const beeDataDefault = computed(() => {
  return [
    {
      name: "基础编程分",
      label: "",
      key: "base",
      score: ''
    },
    {
      name: "程序时间分",
      label: "",
      key: "time",
      score: ''
    },
    {
      name: "飞行器数量分",
      label: "",
      key: "num",
      score: ''
    },
    {
      name: "图案得分",
      label: `满分${ scoreConfigMap.value?.pattern || 0 }分，请输入0到${ scoreConfigMap.value?.pattern || 0 }之间的数值`,
      key: "pattern",
      score: '',
      teacherScore1: '',
      teacherScore2: '',
      teacherScore3: '',
      teacherScore4: '',
      teacherScore5: '',
    },
    {
      name: "动作创意",
      label: `满分${ scoreConfigMap.value?.action || 0 }分，以0.5分为一档，请输入0到${ scoreConfigMap.value?.action || 0 }之间的数值`,
      key: "action",
      score: '',
      teacherScore1: '',
      teacherScore2: '',
      teacherScore3: '',
      teacherScore4: '',
      teacherScore5: '',
    },
    {
      name: "音乐匹配",
      label: `满分${ scoreConfigMap.value?.music || 0 }分，以0.5分为一档，请输入0到${ scoreConfigMap.value?.music || 0 }之间的数值`,
      key: "music",
      score: '',
      teacherScore1: '',
      teacherScore2: '',
      teacherScore3: '',
      teacherScore4: '',
      teacherScore5: '',
    },
  ]
});

const currScore = ref(0);
const isJunior = ref(false);
const isBaseZero = ref(false);
const isGameOver = ref(false);

const scoreConfigMap = computed(() => {
  return scoreConfigTypeMap[isJunior.value ? 'junior' : 'high'];
});

const beeColumn = [
  {
    prop: 'name',
    label: '评分维度',
    score: 0,
    align: 'center',
    width: 350,
  },
  {
    prop: 'teacherScore1',
    label: '评委1',
    score: 5,
    align: 'center',
  },
  {
    prop: 'teacherScore2',
    label: '评委2',
    score: 20,
    align: 'center',
  },
  {
    prop: 'teacherScore3',
    label: '评委3',
    score: 20,
    align: 'center',
  },
  {
    prop: 'teacherScore4',
    label: '评委4',
    score: 20,
    align: 'center',
  },
  {
    prop: 'teacherScore5',
    label: '评委5',
    score: 10,
    align: 'center',
  },
];

const beeData = ref([]);
const scoreConfigTypeMap = {
  junior: {
    base: [
      { val: 0, label: '0分' },
      { val: 20, label: '20分' },
    ],
    time: [
      { val: 0, label: '0分' },
      { val: 10, label: '10分' },
    ],
    num: [
      { val: 6, label: '6分（5台）' },
      { val: 8, label: '8分（6台）' },
      { val: 10, label: '10分（7台）' },
    ],
    pattern: 50,
    action: 20,
    music: 10,
  },
  high: {
    base: [
      { val: 0, label: '0分' },
      { val: 20, label: '20分' },
    ],
    time: [
      { val: 0, label: '0分' },
      { val: 10, label: '10分' },
    ],
    num: [
      { val: 7, label: '7分（7台）' },
      { val: 9, label: '9分（8台）' },
      { val: 12, label: '12分（9台）' },
    ],
    pattern: 48,
    action: 20,
    music: 10,
  }
}

const teacherScoreKeys = [ ...new Array(5) ].map((_, idx) => `teacherScore${ idx + 1 }`);

const onScoreChange = ({ score, key }) => {
  if(key === 'base') {
    if(score === 0) {
      dataInit(true);
    } else {
      isBaseZero.value = false;
    }
  }
}

const onScoreBlur = (row, prop, max) => {
  if (max && row[prop] >= max) {
    row[prop] = max;
  }
}

const spanMethod = ({ rowIndex, columnIndex }) => {
  if(rowIndex < 3 && columnIndex === 1) {
    return { rowspan: 1, colspan: 5 };
  } else if(rowIndex < 3 && columnIndex !== 0) {
    return { rowspan: 0, colspan: 0 };
  }
  return { rowspan: 1, colspan: 1 };
}

watch([
  () => beeData.value
], () => {
  handleScoring();
}, { deep: true, });

onMounted(() => {
  const route = useRoute()
  const id = route.query.id as string;
  const type = route.query.type as string;
  const groupId = route.query.groupId as string;
  queryForm.id = id;
  queryForm.type = type;
  isJunior.value =  groupId === '100301';
  dataInit();
  handleQuery();

  contestInfo.value = {
    id: '',
    company: '',
    matchItemName: '',
    matchItemTeamId: '',
    matchName: '',
    userId: '',
    userName: '',
    teamName: '',
  };

  userInfo.value = {
    name: '',
    code: '',
    school: '',
  };
});

const handleQuery = () => {
  baseService.get("/front/spuser/queryUserByTeamUserId", {
    id: queryForm.id,
    type: queryForm.type
  }).then((res) => {
    if (res.code === 0) {
      setQueryData(res?.data || {});
    }
  });
}

const handleReset = () => {
  queryForm.id = '';
  queryForm.site = '';
  handleQuery();
}

const handleScoring = () => {
  isGameOver.value = false;
  currScore.value = !isGameOver.value && Math.max(0, countScoring()) || 0;
}

const handleCancel = () => {
  dataInit();
}
const handleSubmit = () => {
  if(!checkIsCount()) return ElMessage.error('请先计分');
  if(!isBaseZero.value && !checkIsTeacherScoreFull()) return ElMessage.error('请先完善评委评分');
  const params = getSubmitParams();
  baseService.post("/front/spuser/saveScore", params).then((res) => {
    if (res.code === 0) {
      ElMessage.success('保存成功');
      handleQuery();
      refreshData();
    }
  });
  dataInit();
}

const getSubmitParams = () => {
  // 获取动作创意和音乐匹配的得分
  const actionScore = beeData.value.find(item => item.key === 'action')?.score || 0;
  const musicScore = beeData.value.find(item => item.key === 'music')?.score || 0;

  const params = {
    id: queryForm.id,
    type: queryForm.type,
    userId: contestInfo.value.userId,
    site: queryForm.site,
    matchItemTeamId: contestInfo.value.matchItemTeamId,
    score: currScore.value || 0,
    seconds: actionScore+'',  // 动作创意 → seconds
    num: musicScore+''       // 音乐匹配 → num
  };

  beeData.value.forEach((b, i) => {
    if(i < 3) {
      let newKey = `add${i + 1}`;
      params[newKey] = b.score || 0;
    } else {
      teacherScoreKeys.forEach((key, j) => {
        let newKey = `add${(i - 3) * 5 + j + 4}`;
        params[newKey] = b[key] || 0;
      });
    }
  });
  return params;
}

const setQueryData = (data) => {
  contestInfo.value = data;
  const scoring = data.scoring || {};
  currScore.value = data.score || 0;
  queryForm.site = scoring.site || '';
  isBaseZero.value = scoring.add1 === 0;

  beeData.value.forEach((b, i) => {
    if(i < 3) {
      let newKey = `add${i + 1}`;
      b.score = scoring[newKey] !== undefined && scoring[newKey] !== null ? scoring[newKey] * 1 : '';
    } else {
      teacherScoreKeys.forEach((key, j) => {
        let newKey = `add${(i - 3) * 5 + j + 4}`;
        b[key] = scoring[newKey] !== undefined && scoring[newKey] !== null ? scoring[newKey] : '';
      });
    }
  });
}

const countScoring = () => {
  return beeData.value.reduce((prev: number, cur: any) => {
    let isTeacherScore = !['base', 'time', 'num'].includes(cur.key);
    let keys = isTeacherScore ? teacherScoreKeys : ['score'];
    let total = 0;
    if(isTeacherScore) {
      if(keys.some(k => cur[k] === '')) {
        cur.score = '-';
      } else {
        total = keys.reduce((scoringPrev, scoringKey: string) => {
          return scoringPrev + (cur[scoringKey] || 0) * 1;
        }, 0);
        let scoreArr: number[] = keys.map(k => cur[k] || 0);
        let minScore = Math.min(...scoreArr);
        let maxScore = Math.max(...scoreArr);
        cur.score = total = parseFloat(((total - minScore - maxScore) / 3).toFixed(2));
      }
    } else {
      total = keys.reduce((scoringPrev, scoringKey: string) => {
        return scoringPrev + (cur[scoringKey] || 0) * 1;
      }, 0);
    }
    return prev + total;
  }, 0);
}

const checkIsCount = () => {
  return beeData.value.some(b => {
    let keys = !['base', 'time', 'num'].includes(b.key) ? teacherScoreKeys : ['score'];
    return keys.some(key => b[key] !== '');
  });
}

const checkIsTeacherScoreFull = () => {
  return beeData.value.filter(b => !['base', 'time', 'num'].includes(b.key)).every(b => teacherScoreKeys.every(key => b[key] !== ''));
}

const dataInit = (isZero = false) => {
  console.log("xxxxxxx", )
  beeData.value = beeDataDefault.value.map(item => {
    if(isZero && item.key === 'base') {
      return { ...item, score: 0 }
    }
    return { ...item };
  });
  isGameOver.value = false;
  isBaseZero.value = isZero;
  currScore.value = 0;
}

const refreshData = () => {
  window.parent.postMessage({
    data: "params"
  },'*');
}
</script>

<style lang="scss" scoped>
.scoring-module {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header {
  width: 1140px;
  height: 50px;
  display: flex;
  justify-content: space-between;
  padding: 0 24px;
  box-sizing: border-box;
  align-items: center;
  background: #00A0E9;

  .title {
    color: #fff;
    font-weight: 500;
    font-size: 18px;
  }

  .ico-logo {
    width: 115px;
    height: 40px;
  }
}

.content {
  margin-top: 0px;
  width: 1140px;
  //min-height: 850px;
  padding: 0 24px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 12px;
}

.flying-race-box {
  display: flex;
  align-items: center;
  width: 1090px;
  height: 48px;
  padding: 8px 12px;
  box-sizing: border-box;
  display: flex;
  background: linear-gradient(-90deg, #FBFBFB 0%, #EFF6FF 100%);
  border-radius: 12px;
  .flying-race-logo-wrap {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #00A0E9;
    border-radius: 50%;
    .flying-race-logo {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .flying-race-info {
    margin-left: 16px;
    display: flex;
    align-items: center;
    .flying-race-title {
      color: #333;
      font-size: 14px;
      font-weight: 500;
      line-height: 20px;
    }
  }
  .flying-race-labels {
    margin-left: 24px;
    display: flex;
    align-items: center;
    .flying-race-label {
      color: #333;
      font-size: 12px;
      font-weight: 400;
      line-height: 16px;
      & + .flying-race-label {
        margin-left: 24px;
      }
    }
  }
  .flying-race-tags {
    margin-left: 24px;
    display: flex;
    align-items: center;
    .flying-race-tag {
      color: #00A0E9;
      font-size: 12px;
      font-weight: 400;
      line-height: 16px;
      & + .flying-race-tag {
        margin-left: 16px;
      }
    }
  }
}

.form-query-box {
  margin-top: 24px;
  display: flex;
  align-items: center;
}
.form-box {
  flex: 1;
  overflow: hidden;
  display: flex;
  align-items: center;
  .form-item {
    display: flex;
    align-items: center;
    & + .form-item {
      margin-left: 24px;
    }
    .form-item-label {
      font-weight: 400;
      font-size: 16px;
      color: #333;
      line-height: 22px;
    }
    .form-item-val {
      margin-left: 4px;
      width: 272px;
      height: 32px;
      :deep(.el-input__wrapper) {
        background-color: #fff !important;
      }
    }
  }
  .btn-query {
    margin-left: 18px;
    width: 68px;
    height: 32px;
    border-radius: 6px;
  }
  .btn-reset {
    margin-left: 12px;
    width: 68px;
    height: 32px;
    border-radius: 6px;
  }
}
.scoring-box {
  display: flex;
  align-items: center;
  .btn-scoring {
    width: 62px;
    height: 32px;
    border-radius: 6px;
  }
  .scoring-count {
    margin-left: 12px;
    width: 66px;
    height: 32px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
    border-radius: 6px;
    border: 1px solid rgba(0,160,233,0.4);
    font-size: 18px;
    font-weight: 500;
    color: #333333;
    line-height: 24px;
    text-align: center;
  }
  .scoring-unit {
    margin-left: 8px;
    font-weight: 400;
    font-size: 14px;
    color: #4F5A70;
    line-height: 20px;
  }
}

.scoring-table-box {
  margin-top: 20px;
  .scoring-table-title {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 14px;
    color: #333333;
    line-height: 20px;
    &::before {
      content: '';
      margin-right: 7px;
      width: 3px;
      height: 10px;
      background: #00A0E9;
    }
  }
  .scoring-table-wrap {
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }
  .scoring-table {
    width: 429px;
    border-radius: 0 8px 8px 0;
    border: 1px solid #E4E7EC;
    & + .scoring-table {
      margin-top: 20px;
    }
    :deep() {
      & th, & td {
        border-left: 1px solid #E4E7EC;
        height: 34px;
        padding: 0;
        box-sizing: border-box;
        font-weight: 500;
        font-size: 12px;
        color: #333333;
        line-height: 16px;
      }
      .tr-end {
        height: 28px;
        background: rgba(253,106,110, 0.1);
        font-weight: 500;
        font-size: 14px;
        color: #FD6A6E;
        line-height: 20px;
        &:hover > td {
          background-color: transparent;
        }
        td {
          height: 28px;
          border: 1px solid rgba(253,106,110,0.59);
          .cell {
            line-height: 1;
          }
        }
      }
    }
    .scoring-select {
      width: 90px;
      :deep(.el-select__wrapper) {
        box-shadow: none;
        font-size: 12px;
        .el-select__selected-item {
          text-align: center;
        }
      }
    }
    .scoring-ipt {
      :deep(.el-input__wrapper) {
        box-shadow: none;
        background: #fff !important;
        .el-input__inner {
          font-weight: 500;
          font-size: 12px;
          color: #00A0E9;
          line-height: 16px;
          text-align: center;
        }
      }
      &.scoring-ipt-wran {
        :deep(.el-input__wrapper) {
          .el-input__inner {
            color: #FD6A6E;
          }
        }
      }
    }
    .scoring-radio {
      flex-wrap: nowrap;
      .el-radio {
        & + .el-radio {
         margin-left: 18px;
        }
        :deep(.el-radio__label) {
          font-size: 12px;
        }
      }
    }
    .scoring-base-info {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding: 0 25px;
      box-sizing: border-box;
      .scoring-ipt {
        width: 125px;
      }
    }
    .scoring-dimension-box {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      padding: 10px 0;
      gap: 10px;
      .scoring-dimension-name {
        display: flex;
        align-items: baseline;
        white-space: nowrap;
        font-weight: 500;
        font-size: 15px;
        color: #333;
      }
      .scoring-dimension-label {
        font-weight: 400;
        font-size: 13px;
        color: #b1b3b8;
        line-height: 1;
        text-align: left;
      }
      .scoring-dimension-tips {
        color: #b1b3b8;
      }
    }
  }
  .scoring-time-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 158px;
    height: 67px;
    background: #EFFAFF;
    border-radius: 8px;
    border: 1px solid #DBF4FF;
    .time-label-wrap {
      display: flex;
      align-items: center;
      font-weight: 500;
      font-size: 14px;
      color: #333;
      line-height: 20px;
      .time-label {
        margin-right: 8px;
      }
      .time-count {
        color: #00A0E9;
      }
    }
    .timer-box {
      margin-top: 10px;
      display: flex;
      align-items: center;
      font-weight: 500;
      font-size: 14px;
      color: #333;
      line-height: 20px;
      .timer-item-ipt {
        width: 28px;
        height: 28px;
        :deep() {
          .el-input__wrapper {
            padding: 0;
            border-radius: 6px;
            background-color: #fff !important;
            &:not(.is-focus) {
              box-shadow: none !important;
            }
            .el-input__inner {
              text-align: center;
            }
          }
          input::-webkit-outer-spin-button,
          input::-webkit-inner-spin-button {
            -webkit-appearance: none;
          }
          input[type='number'] {
            -moz-appearance: textfield;
          }
        }
      }
      .timer-split {
        margin: 0 8px;
      }
    }
  }
}

.bee-box {
  display: block;
  margin-top: 40px;
  .scoring-table-title {
    display: none;
  }
  .scoring-table {
    width: 100%;
    border-radius: 8px;
  }
}

.form-btns-box {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  .form-btn {
    width: 74px;
    height: 32px;
    border-radius: 6px;
    & + .form-btn {
      margin-left: 16px;
    }
  }
  .btn-set-zero,
  .btn-set-full {
    color: #00A0E9;
    background: #fff;
    &:hover {
      color: #fff;
      background: #00A0E9;
    }
  }
}

.scoring-end {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 28px;
  box-sizing: border-box;
  font-weight: 500;
  font-size: 12px;
  color: #333333;
  line-height: 16px;
  border: 1px solid rgba(253, 106, 110, 0.59);
  background: rgba(253, 106, 110, 0.1);
}
</style>
